<template>
  <div
    :class="{'avue--collapse':isCollapse}"
    class="avue-contail">
    <div class="avue-header">
      <!-- 顶部导航栏 -->
      <top/>
    </div>

    <div class="avue-layout">
      <div class="avue-left">
        <!-- 左侧导航栏 -->
        <sidebar/>
      </div>
      <div class="avue-main">
        <!-- 顶部标签卡 -->
        <tags/>
        <!-- 主体视图层 -->
        <div style="height:100%;overflow-y:auto;overflow-x:hidden;"
             id="avue-view">
          <keep-alive>
            <router-view class="avue-view"
                         v-if="$route.meta.keepAlive" />
          </keep-alive>
          <router-view class="avue-view"
                       v-if="!$route.meta.keepAlive" />
        </div>
      </div>
    </div>
    <div
      class="avue-shade"
      @click="showCollapse"/>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import tags from './tags'
  import top from './top/'
  import sidebar from './sidebar/'
  import admin from '@/util/admin'
  import {getStore} from '@/util/store.js'
  import * as SockJS from 'sockjs-client'
  import Stomp from 'stomp-websocket'
  import store from '@/store'
  import socketConfig from '@/const/socket'

  export default {
    name: 'Index',
    provide() {
      return {
        Index: this
      };
    },
    components: {
      top,
      tags,
      sidebar
    },
    data() {
      return {
        // 刷新token锁
        refreshLock: false,
        // 刷新token的时间
        // refreshTime: '',
        // 计时器
        timer: ''
      }
    },
    created() {
      // 实时检测刷新token
      // this.refreshToken()
    },
    destroyed() {
      // clearInterval(this.refreshTime)
      clearInterval(this.timer)
      /*
      * 默认关闭websocket，如需工作流通知，则开启
      * this.disconnect()
      */

      // 关闭websocket连接
      this.disconnect()
    },
    mounted() {
      this.init()
      /*
       * 默认关闭websocket，如需工作流通知，则开启
       * this.initWebSocket()
      */
      // 建立websocket连接
      this.initWebSocket()
    },
    computed: mapGetters(['userInfo', 'isLock', 'isCollapse', 'website', 'expires_in']),
    methods: {
      showCollapse() {
        this.$store.commit('SET_COLLAPSE')
      },
      openMenu(item = {}) {
        this.$store.dispatch("GetMenu",{type: true,id: item.id}).then(data => {
            if (data.length !== 0) {
                this.$router.$avueRouter.formatRoutes(data, true);
            }
        });
      },
      // 屏幕检测
      init() {
        this.$store.commit('SET_SCREEN', admin.getScreen())
        window.onresize = () => {
          setTimeout(() => {
            this.$store.commit('SET_SCREEN', admin.getScreen())
          }, 0)
        }
      },
      // // 实时检测刷新token
      // refreshToken() {
      //   this.refreshTime = setInterval(() => {
      //     const token = getStore({
      //       name: 'access_token',
      //       debug: true
      //     })
      //     if (this.validatenull(token)) {
      //       return
      //     }
      //     if (this.expires_in <= 1000 && !this.refreshLock) {
      //       this.refreshLock = true
      //       this.$store
      //         .dispatch('RefreshToken')
      //         .catch(() => {
      //           clearInterval(this.refreshTime)
      //         })
      //       this.refreshLock = false
      //     }
      //     this.$store.commit('SET_EXPIRES_IN', this.expires_in - 10)
      //   }, 10000)
      // },
      initWebSocket() {
        this.connection()
      },
      connection() {
        const token = store.getters.access_token
        const TENANT_ID = getStore({name: 'tenantId'}) ? getStore({name: 'tenantId'}) : 'DB_0'
        const headers = {
          'Authorization': 'Bearer ' + token,
          'TENANT-ID':  TENANT_ID
        }

        const endpoint = socketConfig.SOCKET_ENDPOINT + '?Authorization=' + token + '&TENANT-ID=' + TENANT_ID
        this.socket = new SockJS(endpoint, headers, {timeout: 15000})
        // 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(this.socket)
        this.stompClient.debug = null
        // 向服务器发起websocket连接
        this.stompClient.connect({}, () => {
          console.log("连接成功")
          const self = this
          // 断开重连机制,尝试发送消息,捕获异常发生时重连
          this.timer = setInterval(() => {
            try {
              self.stompClient.send('test')
            } catch (err) {
              console.log('断线了: ' + err)
              self.connection()
            }
          }, 60000)
          this.autoSubscribe()
        }, (err) => {
          console.error("连接失败", err)
        })
      },

      autoSubscribe() {
        const subscribeTopic = '/topic/restReminder'
        if (this.stompClient) {
          this.stompClient.subscribe(subscribeTopic, (resp) => { // 订阅服务端提供的某个topic;
            console.log('收到消息', resp.body)
            this.$notify({
              title: '休息提醒',
              type: 'warning',
              dangerouslyUseHTMLString: true,
              message: resp.body,
              position: 'bottom-right',
              offset: 60
            })
          })
          console.log('订阅成功： ' + subscribeTopic)
        } else {
          console.log("建立连接失败")
        }
      },
      disconnect() {
        if (this.stompClient) {
          this.stompClient.disconnect()
          console.log('Disconnected')
        }
      }
    }
  }
</script>
